new Vue({
  el: '#app',
  data() {
    return {
      fileList: [],
      tableData: [],
      form: {
        page: 1,
        limit: 15,
      },
      loading: false,
      success: 0,
      error: 0,
      Start_Date: '',
      End_Date: '',
      submitData: [],//提交
      Supplier_Article_Stock_SerialNumber: '',
      obj:{},
    }
  },
  mixins: [importMixin],
  mounted() {
    this.obj = JSON.parse(sessionStorage.getItem("Initialization")) 
  },
  methods: {
    submitUpload(i = 0) {
      const that = this;
      if (i < this.tableData.length) {
        if (i == 0) {//首次初始化
          this.success = 0;
          this.error = 0;
        }
        this.loading = true;
        if (!this.tableData[i].Article_SerialNumber) {
          this.tableData[i].isStatus = '2';
          this.tableData[i].Cause = '商品内码不能为空'
          this.error++;
          this.submitUpload(i + 1);
        } else if (!(this.tableData[i].Quantity > 0)) {
          this.tableData[i].isStatus = '2';
          this.tableData[i].Cause = '入库数量需大于0'
          this.error++;
          this.submitUpload(i + 1);
        } else { //校验通过
          //查询仓库有无该商品，
          $.ajax({
            headers: requestHeaders(),
            url: `${BASE_URL2}/member/getMemberPoint`,
            type: 'POST',
            data: {
              Data: JSON.stringify([{
                  tableName: 'warehouse_inventory',
                  Condition: window.btoa(unescape(encodeURIComponent("Article_SerialNumber='" + that.tableData[i].Article_SerialNumber + "' AND Warehouse_SerialNumber='"+that.obj.Warehouse_SerialNumber+"' AND Enterprise_Info_SerialNumber='"+$.cookie('enterprise')+"'"))),
              }, {
                  tableName: 'warehouse_info',
                  Condition: window.btoa(unescape(encodeURIComponent("Warehouse_SerialNumber='" + that.obj.Warehouse_SerialNumber+"'"))),
              }]),
            },
            success: function ({warehouse_inventory,warehouse_info}) {
              warehouse_info[0].Warehouse_Initialize = '1'
              let data = {
                Modify:{
                  warehouse_info,
                }
              };
              if (warehouse_inventory.length == 0) {
                warehouse_inventory.push({
                  Warehouse_Inventory_SerialNumber:'',
                  Warehouse_SerialNumber:that.obj.Warehouse_SerialNumber,
                  Article_SerialNumber:that.tableData[i].Article_SerialNumber ,
                  Inventory_Total_Quantity:that.tableData[i].Quantity,
                  Remain_Quantity:that.tableData[i].Quantity,
                  Enterprise_Info_SerialNumber:$.cookie('enterprise')
                })
                data['Add'] = {
                  warehouse_inventory
                }
              }else{
                warehouse_inventory[0].Inventory_Total_Quantity = accAdd(warehouse_inventory[0].Inventory_Total_Quantity,that.tableData[i].Quantity);
                warehouse_inventory[0].Remain_Quantity = accAdd(warehouse_inventory[0].Remain_Quantity,that.tableData[i].Quantity);
                data.Modify['warehouse_inventory'] = warehouse_inventory;
              }
              that.submitForm({ Data: JSON.stringify(data) }, (res) => {
                if (res.Status == 'success') {
                  that.tableData[i].isStatus = '1';
                  that.tableData[i].Cause = '',
                  that.success++;
                } else {
                  that.tableData[i].isStatus = '2';
                  that.tableData[i].Cause = '未知错误'
                  that.error++;
                }
                that.submitUpload(i + 1);
              })
            },
            complete: function (XMLHttpRequest) {
              requestPretreatment(XMLHttpRequest);
            },
            dataType: "json"
          })
        }
      } else if (i != 0) {
        this.loading = false;
        this.$message.success("批量导入结束")
      } else {
        this.$message({
          message: '请先导入模板后再上传',
          type: 'warning'
        })
      }
    },
    submitForm(data, callback) {
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalSave`,
        type: 'POST',
        data,
        success: function (res) {
          callback(res)
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json"
      })
    },
    handleChange({ raw }) {//导入监听文件
      const that = this;
      var reader = new FileReader();
      reader.readAsBinaryString(raw);
      reader.onload = function (e) {
        var data = e.target.result;
        var wb = XLSX.read(data, {
          type: 'binary' //以二进制的方式读取
        });
        var sheet = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
        var json = XLSX.utils.sheet_to_json(sheet);//利用接口实现转换。
        let Article = [];
        let sql1 = "";
        json.forEach((item, index) => {
          let Article_SerialNumber = item['商品内码'] ? item['商品内码'] : ''
          if (!Article.some(i => i == Article_SerialNumber)) {
            Article.push(Article_SerialNumber);
            if (index == 0) {
              sql1 = sql1 + "article_info.Article_SerialNumber='" + Article_SerialNumber + "'\r\n"
            } else {
              sql1 = sql1 + " or article_info.Article_SerialNumber='" + Article_SerialNumber + "'\r\n"
            }
          }
        })
        //查询商品信息
        $.ajax({
          headers: requestHeaders(),
          type: 'POST',
          url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
          data: {
            SQLSerialNumber: 'A_article_info',
            Condition: '',
            ExtensionCondition: window.btoa(unescape(encodeURIComponent(`and (${sql1})`))),
          },
          success: function (Result) {
            let arr = [];
            json.forEach(item => {
              let Article_SerialNumber = item['商品内码'] ? item['商品内码'] : ''
              let Quantity = item['入库数量'] ? item['入库数量'] : 0
              if (Result.some(i => i.Article_SerialNumber == Article_SerialNumber)) {
                arr.push({
                  ...Result.filter(i => i.Article_SerialNumber == Article_SerialNumber)[0],
                  Warehouse_Inventory_SerialNumber: '',
                  Warehouse_SerialNumber: '',
                  Quantity,
                  isEdit: false,
                  isStatus: '0',
                  Cause: '',
                })
              } else {
                arr.push({
                  ...Result.filter(i => i.Article_SerialNumber == Article_SerialNumber)[0],
                  Warehouse_Inventory_SerialNumber: '',
                  Warehouse_SerialNumber: '',
                  Quantity,
                  isEdit: false,
                  isError: true,
                  isStatus: '2',
                  Cause: '该商品未查到,可能原因:\r\n1.该商品内码不正确',
                })
              }
            });
            that.tableData = arr
          },
          complete: function (XMLHttpRequest) {
            requestPretreatment(XMLHttpRequest);
          },
          dataType: "json"
        })
      }
    },
    handleSizeChange(val) {
      this.form.page = 1;
      this.form.limit = val;
    },
    handleCurrentChange(val) {
      this.form.page = val;
    },
    handleEdit(row) {//修改当前行
      row.isEdit = !row.isEdit
    },
    handleRemove(index) {//移除当前行
      this.$confirm('是否要删除此行?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.tableData = this.tableData.filter((i, id) => id != (this.form.page - 1) * this.form.limit + index)
      }).catch(() => { });
    },
    handleClean() {//清空
      this.$confirm('是否要清空导入数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.tableData = []
      }).catch(() => { });
    },
  },
})